{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ac2861b1",
   "metadata": {},
   "source": [
    "* 本周主要内容：语音识别\n",
    "* 时间：week13\n",
    "* 记录人：赖文佩\n",
    "* 期末考流程！！！"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05f7a951",
   "metadata": {},
   "source": [
    "# 语音录制      \n",
    "* 安装 下载模块:pip install 模块名称          \n",
    "> SpeechRecognition     \n",
    "> Pyaudio        \n",
    "> Pydub"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2962c2d5",
   "metadata": {},
   "source": [
    "# 语音识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "7af0b653",
   "metadata": {},
   "outputs": [],
   "source": [
    "import bdasr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "3dc8d494",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 准备自己的key\n",
    "API_KEY = '0lrXE5VkFzVV8RSl2LNBIgQA'\n",
    "SECRET_KEY = 'l9lWYFjzKE0tqR8jWz1CGgAOXRdUvNpS'\n",
    "\n",
    "# 文件路径\n",
    "AUDIO_FILE = 'D:/API-AL-ML/api-al-ml/week12/speech-demo-master/rest-api-asr/python/audio/16k.pcm'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "3fd862c6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from bdasr import fetch_token,asr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2cd8a3f",
   "metadata": {},
   "source": [
    "# 1.语音识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "02f2928b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.30d37d9c103fdb26cbb4f59cdee80fe3.315360000.2000082143.282335-33297582\",\"expires_in\":2592000,\"session_key\":\"9mzdXvFpzWl3AJn68OkclkuOa6dqoBYC7K\\/pBrlkJz3Zg9iUKnh+y8TTUHRUGDjg0FfA0\\/dkyOrcQJP1i8STKhtk1i0VsQ==\",\"access_token\":\"24.e45a98d5f2f7ccd0d375bc0562b92e25.2592000.1687314143.282335-33297582\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"d90a28729f9f96c0000da524cd2c819c\"}\n",
      "\n",
      "{'refresh_token': '25.30d37d9c103fdb26cbb4f59cdee80fe3.315360000.2000082143.282335-33297582', 'expires_in': 2592000, 'session_key': '9mzdXvFpzWl3AJn68OkclkuOa6dqoBYC7K/pBrlkJz3Zg9iUKnh+y8TTUHRUGDjg0FfA0/dkyOrcQJP1i8STKhtk1i0VsQ==', 'access_token': '24.e45a98d5f2f7ccd0d375bc0562b92e25.2592000.1687314143.282335-33297582', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': 'd90a28729f9f96c0000da524cd2c819c'}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.e45a98d5f2f7ccd0d375bc0562b92e25.2592000.1687314143.282335-33297582  EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 1.214620\n",
      "{\"corpus_no\":\"7235826512532893816\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"727961687551684722144\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "xu_token = bdasr.fetch_token(API_KEY,SECRET_KEY)\n",
    "bdasr.asr(xu_token,AUDIO_FILE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "49da45a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Requirement already satisfied: speechrecognition in c:\\users\\lenovo\\appdata\\roaming\\python\\python39\\site-packages (3.10.0)\n",
      "Requirement already satisfied: requests>=2.26.0 in d:\\anaconda\\lib\\site-packages (from speechrecognition) (2.27.1)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\anaconda\\lib\\site-packages (from requests>=2.26.0->speechrecognition) (2021.10.8)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in d:\\anaconda\\lib\\site-packages (from requests>=2.26.0->speechrecognition) (2.0.4)\n",
      "Requirement already satisfied: idna<4,>=2.5 in d:\\anaconda\\lib\\site-packages (from requests>=2.26.0->speechrecognition) (3.3)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\anaconda\\lib\\site-packages (from requests>=2.26.0->speechrecognition) (1.26.9)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install speechrecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "4c8a6d59",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Requirement already satisfied: pyaudio in c:\\users\\lenovo\\appdata\\roaming\\python\\python39\\site-packages (0.2.13)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install pyaudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7aa0b260",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "1737c769",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 1.195395\n",
      "{\"corpus_no\":\"7235826563972865262\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"可能没有去买过嗯。\"],\"sn\":\"548683837811684722156\"}\n",
      "\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "eval() arg 1 must be a string, bytes or code object",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[1;32mIn [26]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m asr_output \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43meval\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43masr\u001b[49m\u001b[43m(\u001b[49m\u001b[43mxu_token\u001b[49m\u001b[43m,\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43m1.wav\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m'\u001b[39m][\u001b[38;5;241m0\u001b[39m]\n\u001b[0;32m      2\u001b[0m asr_output\n",
      "\u001b[1;31mTypeError\u001b[0m: eval() arg 1 must be a string, bytes or code object"
     ]
    }
   ],
   "source": [
    "asr_output = eval(asr(xu_token,'1.wav'))['result'][0]\n",
    "asr_output"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c98530b",
   "metadata": {},
   "source": [
    "# 2.回复（接入open ai）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83deed79",
   "metadata": {},
   "source": [
    "* pip install openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5b827f27",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple\n",
      "Collecting openai\n",
      "  Using cached https://pypi.tuna.tsinghua.edu.cn/packages/9f/87/838149e472c58a141fa81e2eb4cc8828cb134054b59d67637031985ca770/openai-0.27.6-py3-none-any.whl (71 kB)\n",
      "Requirement already satisfied: tqdm in d:\\anaconda\\lib\\site-packages (from openai) (4.64.0)\n",
      "Requirement already satisfied: aiohttp in d:\\anaconda\\lib\\site-packages (from openai) (3.8.1)\n",
      "Requirement already satisfied: requests>=2.20 in d:\\anaconda\\lib\\site-packages (from openai) (2.27.1)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\anaconda\\lib\\site-packages (from requests>=2.20->openai) (1.26.9)\n",
      "Requirement already satisfied: idna<4,>=2.5 in d:\\anaconda\\lib\\site-packages (from requests>=2.20->openai) (3.3)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\anaconda\\lib\\site-packages (from requests>=2.20->openai) (2021.10.8)\n",
      "Requirement already satisfied: charset-normalizer~=2.0.0 in d:\\anaconda\\lib\\site-packages (from requests>=2.20->openai) (2.0.4)\n",
      "Requirement already satisfied: yarl<2.0,>=1.0 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (1.6.3)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (1.2.0)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (5.1.0)\n",
      "Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (4.0.1)\n",
      "Requirement already satisfied: attrs>=17.3.0 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (21.4.0)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in d:\\anaconda\\lib\\site-packages (from aiohttp->openai) (1.2.0)\n",
      "Requirement already satisfied: typing-extensions>=3.6.5 in d:\\anaconda\\lib\\site-packages (from async-timeout<5.0,>=4.0.0a3->aiohttp->openai) (4.1.1)\n",
      "Requirement already satisfied: colorama in d:\\anaconda\\lib\\site-packages (from tqdm->openai) (0.4.4)\n",
      "Installing collected packages: openai\n",
      "Successfully installed openai-0.27.6Note: you may need to restart the kernel to use updated packages.\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  WARNING: The script openai.exe is installed in 'C:\\Users\\lenovo\\AppData\\Roaming\\Python\\Python39\\Scripts' which is not on PATH.\n",
      "  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.\n"
     ]
    }
   ],
   "source": [
    "pip install openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a241e7df",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai\n",
    "#主循环\n",
    "def openai_chat(question):\n",
    "    api_key = \"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\"\n",
    "    openai.api_key = api_key\n",
    "\n",
    "    #获取用户输入的问题\n",
    "    #question = input(\"请输入问题：\")\n",
    "\n",
    "    #调用openai的api\n",
    "    completion = openai.ChatCompletion.create(\n",
    "        model=\"gpt-3.5-turbo\",\n",
    "        messages=[{\"role\": \"user\",\n",
    "                     \"content\": question}],\n",
    "        max_tokens=4000,\n",
    "        temperature=0.8,\n",
    "    )\n",
    "    #打印答案\n",
    "    return completion[\"choices\"][0][\"message\"][\"content\"]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a44dff6a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "3a04d2b5",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'asr_output' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Input \u001b[1;32mIn [27]\u001b[0m, in \u001b[0;36m<cell line: 1>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[0m chat \u001b[38;5;241m=\u001b[39m chat\u001b[38;5;241m.\u001b[39mopenai_chat(\u001b[43masr_output\u001b[49m)\n\u001b[0;32m      2\u001b[0m chat\n",
      "\u001b[1;31mNameError\u001b[0m: name 'asr_output' is not defined"
     ]
    }
   ],
   "source": [
    "chat = chat.openai_chat(asr_output)\n",
    "chat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "508e7343",
   "metadata": {},
   "source": [
    "# 3，语音合成"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab88e952",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
